package com.umakr.ax.security.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.umakr.ax.security.core.jwt.JwtConfigProperties;
import com.umakr.ax.security.model.Role;
import com.umakr.ax.security.model.SecurityUser;
import com.umakr.ax.security.model.User;
import com.umakr.ax.security.model.UserRole;
import com.umakr.ax.security.model.vo.UserMenuVO;
import com.umakr.ax.security.model.vo.UserVO;
import com.umakr.ax.security.service.RadioStationsService;
import com.umakr.ax.security.service.RoleService;
import com.umakr.ax.security.service.UserRoleService;
import com.umakr.ax.security.service.UserService;
import com.umakr.ax.utils.FormatPhotoUrlUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author gx
 * @since 2017/5/15
 */
@Controller
@RequestMapping("/api/system/user/")
public class PermissionUserController {
    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RadioStationsService radioStationService;

    @Autowired
    JwtConfigProperties jwtConfigProperties;
    @Autowired
    Environment env;

    private static final String STATUS = "1";
    private static final String USERDETAILS_RSID = "rsId";
    private static final Integer STATIONSTATUS_FREEZE = 2;
    private static final Integer STATIONSTATUS_DELETE = 3;
    private static final String ERROR_CODE = "errorCode";
    private static final String TOKEN = "token";
    private static final String AVATAR = "avatar";


    /**
     * (H-F)24
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    @RequestMapping("/login")
    @ResponseBody
    public Object login(String username,String password){
        String aliUrl = env.getProperty("oss.img.path");
        String token = "";
        Map<String,Object> map = Maps.newHashMap();
        try {
            token = userService.login(username,password);
            Long userId = ((SecurityUser)(SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getId();
            map.put(ERROR_CODE,1);
            map.put("msg","");
            Map<String,Object> dataMap = Maps.newHashMap();

            dataMap.put(TOKEN,token);
            dataMap.put("userId", userId);
            Map<String,Object> userDetails = userService.getUserDetailsByUserId(userId);

            if(userDetails != null) {
                String status = userDetails.get("status").toString();
                if(STATUS.equals(status)) {
                    if(userDetails.get(USERDETAILS_RSID) != null) {
                        String rsId = userDetails.get("rsId").toString();
                        Integer stationStatus = radioStationService.getRadioStationStatusByUserId(Long.parseLong(rsId));
                        if(stationStatus != null) {
                            if(stationStatus == 0) {
                                map.put("msg","此电台暂未开通");
                                map.put(ERROR_CODE,0);
                            } else if(Objects.equals(stationStatus, STATIONSTATUS_FREEZE)) {
                                map.put("msg","此电台已冻结");
                                map.put(ERROR_CODE,0);
                            } else if(Objects.equals(stationStatus, STATIONSTATUS_DELETE)) {
                                map.put("msg","此电台已删除");
                                map.put(ERROR_CODE,0);
                            } else{
                                dataMap.putAll(userDetails);
                                List<Role> roleList = roleService.queryRoleByUserId(userId);
                                StringBuilder roles = new StringBuilder("");
                                for (Role role : roleList){
                                    roles.append(role.getRoleCode());
                                    roles.append(",");
                                }
                                dataMap.put("roles",roles.toString());
                                logger.info("login============================================roles"+roles.toString());
                                dataMap.put(AVATAR, FormatPhotoUrlUtil.formatString(aliUrl,userDetails.get(AVATAR)));
                            }
                        }
                    } else{
                        dataMap.putAll(userDetails);
                        List<Role> roleList = roleService.queryRoleByUserId(userId);
                        StringBuilder roles = new StringBuilder("");
                        for (Role role : roleList){
                            roles.append(role.getRoleCode());
                            roles.append(",");
                        }
                        dataMap.put("roles",roles.toString());
                        dataMap.put(AVATAR, FormatPhotoUrlUtil.formatString(aliUrl,userDetails.get(AVATAR)));
                    }
                } else {
                    map.put("msg","此账号已被冻结");
                    map.put(ERROR_CODE,0);
                }

            }
            map.put("data",dataMap);

        }catch (BadCredentialsException e){
            map.put("msg","用户名或密码错误");
            map.put(ERROR_CODE,0);
        }
        logger.info("login=========================================================="+map);
    return map;
}




    /**
     * @return token
     */
    @RequestMapping("/refreshToken")
    @ResponseBody
    public Object refreshToken(String token){
        Map<String,Object> map = Maps.newHashMap();
        try {
            map.put(TOKEN,token);
            map.put(ERROR_CODE,1);
        }catch (BadCredentialsException e){
            map.put(TOKEN,"用户名或密码错误");
            map.put(ERROR_CODE,0);
        }
        return map;
    }

    /**
     * 决策器认证
     * @param appKey 系统颁发给决策器的key
     * @param appSecure 系统颁发给决策器的秘钥
     * @return jsonObject
     */
    @RequestMapping("/getAccessToken")
    @ResponseBody
    public Object getAccessToken(String appKey,String appSecure){
        return Maps.newHashMap();
    }
    /**
     * (H-F)14
     * 新增用户信息
     * @param user 用户信息
     * @return 操作是否成功
     */
    @ApiOperation("新增用户信息")
    @RequestMapping("/addUser")
    @ResponseBody
    public Object addUser(UserVO user){
        if(!userService.exitUsername(user.getUsername())){
            userService.update(user.toUser());
        }
        return userService.resultMap(1,"");
    }


    /**
     * (H-F)15
     * 更新用户信息
     * @param user 用户信息
     * @return 操作是否成功
     */
    @ApiOperation("更新用户信息")
    @RequestMapping("/userUpdate")
    @ResponseBody
    public Object userUpdate(UserVO user){
        if(user.getUserid() != null){
            User userOld  = userService.selectById(user.getUserid());
            BeanUtils.copyProperties(user.toUser(),userOld);
            userService.update(userOld);
        }
        return userService.resultMap(1,"");
    }

    /**
     * (H-F)16
     * 查询用户信息
     * @param user 查询条件
     * @return 结果
     */
    @ApiOperation("查询用户信息")
    @RequestMapping("/userQuery")
    @ResponseBody
    public Object userQuery(UserVO user){
        Map<String,Object> map = userService.resultMap(1,"");
        map.put("data",userService.queryUserPage(user));
        return map;
    }

    /**
     * (H-F)17
     * 绑定用户角色
     * @param userId 用户id
     * @param roleId 角色id
     * @return 返回操作是否成功
     */
    @ApiOperation("绑定用户角色")
    @RequestMapping("/bindUser")
    @ResponseBody
    public Object bindUser(Long userId,Long roleId){
        if(userId == null){
            return userService.resultMap(0,"userId is null");
        }
        if(roleId == null){
            return userService.resultMap(0,"roleId is null");
        }

       User user =  userService.selectById(userId);
       if(user == null){
           return userService.resultMap(0,"user is not exit.");
       }
       Role role =  roleService.selectById(roleId);
       if(role == null){
           return userService.resultMap(0,"role is not exit.");
       }

       EntityWrapper<UserRole> entityWrapper = new EntityWrapper<>();
       entityWrapper.eq("user_id",userId);
       entityWrapper.eq("role_id",roleId);
       List<UserRole> userRoleList = userRoleService.selectList(entityWrapper);
       if(userRoleList.isEmpty()){
           UserRole userRole = new UserRole();
           userRole.setRoleId(roleId);
           userRole.setUserId(userId);
           userRoleService.update(userRole);
       }
       return userService.resultMap(1,"");
    }

    /**
     * (H-F)18
     * 取消用户角色
     * @param userId 用户id
     * @param roleId 角色id
     * @return 返回操作是否成功
     */
    @ApiOperation("取消用户角色")
    @RequestMapping("/unbindUser")
    @ResponseBody
    public Object unbindUser(Long userId,Long roleId){
        if(userId == null){
            return userService.resultMap(0,"userId is null");
        }
        if(roleId == null){
            return userService.resultMap(0,"roleId is null");
        }

        User user =  userService.selectById(userId);
        if(user == null){
            return userService.resultMap(0,"user is not exit.");
        }
        Role role =  roleService.selectById(roleId);
        if(role == null){
            return userService.resultMap(0,"role is not exit.");
        }

        EntityWrapper<UserRole> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("user_id",userId);
        entityWrapper.eq("role_id",roleId);
        List<UserRole> userRoleList = userRoleService.selectList(entityWrapper);
        if(!userRoleList.isEmpty()){
            for(UserRole userRole : userRoleList){
                userRoleService.delete(userRole.getId());
            }
        }
        return userService.resultMap(1,"");
    }
    /**
     * (H-F)25
     * 用户菜单展示
     * @param userId 用户id
     * @return 返回操作是否成功
     */
    @ApiOperation("用户菜单展示")
    @RequestMapping("/showMenuByRole")
    @ResponseBody
    public Object showMenuByRole(Long userId){
        List<UserMenuVO> userMenuVOList = userService.queryUserMenu(userId);
        return userService.resultMap(userMenuVOList);
    }
    /**
     * (H-F)26
     * 用户资源展示
     * @param userId 用户id
     * @return 返回操作是否成功
     */
    @ApiOperation("用户资源展示")
    @RequestMapping("/showResourceByRole")
    @ResponseBody
    public Object showResourceByRole(Long userId){
        return userService.resultMap(1,"");
    }
}
